﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using Microsoft.SharePoint.Client.Services;
using System.ServiceModel.Activation;
using PeoplePickerPlus.Entities;
using PeoplePickerPlus.Helpers;
using System.Web;
using System.ServiceModel.Web;
using System.Net;

namespace PeoplePickerPlus.Services
{
    [BasicHttpBindingServiceMetadataExchangeEndpointAttribute]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
    [ServiceBehavior(AddressFilterMode = AddressFilterMode.Any)]
    public class Entities: IEntities
    {
        public string GetVersion()
        {
            return "1.0";
        }


        public EntitiesResponse GetEntities(EntityRequest request)
        {
            if (!EnsureAuthenticated())
            {
                return null;
            }

            EntitiesResponse response = new EntitiesResponse();

            try
            {
                response.Groups = EntityManager.GetEntities(request);
            }
            catch (Exception ex)
            {
                response.Error = ex.Message;
            }

            return response;
        }

        protected bool EnsureAuthenticated()
        {
            if (ShouldForceAuthentication(HttpContext.Current))
            {
                WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.Unauthorized;
                WebOperationContext.Current.OutgoingResponse.SuppressEntityBody = true;
                return false;
            }
            return true;
        }

        public static bool ShouldForceAuthentication(HttpContext httpContext)
        {
            return httpContext != null && (httpContext.User == null || httpContext.User.Identity == null || !httpContext.User.Identity.IsAuthenticated);
        }


        public EntitiesResponse GetMembers(string groupId)
        {
            if (!EnsureAuthenticated())
            {
                return null;
            }

            EntitiesResponse response = new EntitiesResponse();

            try
            {
                response.Groups = EntityManager.GetMembers(groupId);
            }
            catch (Exception ex)
            {
                response.Error = ex.Message;
            }

            return response;
        }
    }
}
